/**
 * Created by lenovo-pc on 2017/10/13.
 */


window.addEventListener("load", function () {
    BankCardAccountSearchEventHandler.init();
    BankCardAccountTableBox.init();
});


function EnmuToStringForCardType(type) {
    var temp;
    switch (type) {
        case 'DEPOSIT':
            temp = "储蓄卡";
            break;
        case 'CREDIT':
            temp = "信用卡";
            break;
    }
    return temp;
}

function EnmuToStringForFundAcctOpened(type) {
    var temp;
    switch (type) {
        case 'NOT_OPENED':
            temp = "未开通";
            break;
        case 'OPENED':
            temp = "已开通";
            break;
    }
    return temp;
}

function EnmuToStringForAvailable(type) {
    var temp;
    switch (type) {
        case 'NOT_AVAILABLE':
            temp = "不可用";
            break;
        case 'AVAILABLE':
            temp = "可用";
            break;
    }
    return temp;
}
function EnmuToStringForBankCode(type) {
    var temp;
    switch (type) {
        case 'CMBC':
            temp = "中国民生银行";
            break;
        case 'BOC':
            temp = "中国银行";
        case 'CCB':
            temp = "中国建设银行";
            break;
        case 'SPDB':
            temp = "浦东发展银行";
        case 'BOS':
            temp = "上海银行";
            break;
        case 'ABC':
            temp = "中国农业银行";
            break;
        case 'CNCB':
            temp = "中信银行";
            break;
        case 'CIB':
            temp = "兴业银行";
        case 'HXB':
            temp = "华夏银行";
            break;
        case 'CGB':
            temp = "广东发展银行";
            break;
        case 'PSBC':
            temp = "中国邮政储蓄银行";
            break;
        case 'ICBC':
            temp = "中国工商银行";
            break;
        case 'CMB':
            temp = "中国光大银行";
            break;
        case 'BOCOM':
            temp = "交通银行";
            break;
        case 'CEB':
            temp = "华夏银行";
            break;
        case 'PAB':
            temp = "平安银行";
            break;
        case 'BOB':
            temp = "北京银行";
            break;
    }
    return temp;
}

const BankCardAccountSearchEventHandler = {

    init: function () {
        var e, _this;
        _this = this;
        e = document.querySelector("#bankCardAccountSearchBtn");
        e.addEventListener("click", function () {
            _this.search(this);
        });
    }
    , search: function (btn) {
        var form, field, params;
        form = btn.form;
        field0 = form.querySelector("input[name='userId']");
        field1 = form.querySelector("input[name='identifier']");
        params = new Params();

        if (field0.value) {
            params.userId = field0.value;
        }
        if (field1.value) {
            params.identifier = field1.value;
        }
        BankCardAccountTableBox.refresh(form.action, params);
    }


};

function Params() {
}


const BankCardAccountTableBox = {


    _url_: null,

    _tableBox_: null,

    _params_: null,

    _overlayDiv_: null,

    _draw_: 0,

    _dataTable_: null,

    _language_: {
        processing: "飞速加载中",
        emptyTable: "没有搜索到符合的结果",
        zeroRecord: "没有匹配的结果",
        paginate: {
            first: "首页",
            last: "尾页",
            previous: "上一页",
            next: "下一页"
        },
        select: {
            rows: "%d 行已选择"
        },
        info: "显示 _START_ 至 _END_   共 _TOTAL_ 行",
        infoFiltered: "",
        lengthMenu: "每页显示 _MENU_ 行",
        search: "过滤:"
    },

    _createButton_: {
        className: "btn btn-primary Add",
        text: "添加",
        action: function (e, dt, node, config) {
            BankCardAccountTableEventHandler.buttonAdd(e, dt, node, config);
        }
    },

    _updateButton_: {
        className: "btn btn-primary Edit disabled onlyOne",
        text: "编辑",
        action: function (e, dt, node, config) {
            BankCardAccountTableEventHandler.buttonEdit(e, dt, node, config);
        }
    },

    _deleteButton_: {
        className: "btn btn-danger Del disabled onlyOne",
        text: "删除",
        action: function (e, dt, node, config) {
            BankCardAccountTableEventHandler.buttonDelete(e, dt, node, config);
        }
    },

    _columns_: [
        {
            "searchable": false,
            //"title":"name",
            "className": "id text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.id == "" ? "--" : row.id;
                        break;
                    case 'set':
                        row.name = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "id",
            "orderable": false,
            "type": "num"

        },
        {
            "searchable": false,
            //"title":"地址",
            "className": "userId text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.user.id == "" ? "--" : row.user.id;
                        break;
                    case 'set':
                        row.position = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "userId",
            "orderable": false,
            "type": "num"

        },
        {
            "searchable": false,
            //"title":"地址",
            "className": "bankCode text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.bankCode == "" ? "--" : EnmuToStringForBankCode(row.bankCode);
                        break;
                    case 'set':
                        row.position = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "bankCode",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            //"title":"更新时间",
            "className": "cardType text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = EnmuToStringForCardType(row.cardType);
                        break;
                    case 'set':
                        row.salary = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "cardType",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            //"title":"更新时间",
            "className": "bankCardNo text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.bankCardNo == "" ? "--" : row.bankCardNo;
                        break;
                    case 'set':
                        row.salary = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "bankCardNo",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            //"title":"更新时间",
            "className": "issueMobileNo text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.issueMobileNo == "" ? "--" : row.issueMobileNo;
                        break;
                    case 'set':
                        row.salary = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "issueMobileNo",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            //"title":"更新时间",
            "className": "available text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = EnmuToStringForAvailable(row.available);
                        break;
                    case 'set':
                        row.salary = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "available",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            //"title":"更新时间",
            "className": "fundAccountOpened text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = EnmuToStringForFundAcctOpened(row.fundAccountOpened);
                        break;
                    case 'set':
                        row.salary = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "fundAccountOpened",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            //"title":"更新时间",
            "className": "fundAccountOpenTime text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.fundAccountOpenTime == "" ? "--" : row.fundAccountOpenTime;
                        break;
                    case 'set':
                        row.salary = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "fundAccountOpenTime",
            "orderable": false,
            "type": "date"

        },
        {
            "searchable": false,
            //"title":"更新时间",
            "className": "fundTradeAccount text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.fundTradeAccount == "" ? "--" : row.fundTradeAccount;
                        break;
                    case 'set':
                        row.salary = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "fundTradeAccount",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            //"title":"更新时间",
            "className": "bindTime text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.bindTime == "" ? "--" : row.bindTime;
                        break;
                    case 'set':
                        row.salary = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "bindTime",
            "orderable": false,
            "type": "date"

        },
        {
            "searchable": false,
            //"title":"更新时间",
            "className": "unbindTime text-nowrap text-center",
            "data": function (row, type, val, meta) {
                var cellData;
                switch (type) {
                    case 'display':
                        cellData = row.unbindTime == "" ? "--" : row.unbindTime;
                        break;
                    case 'set':
                        row.salary = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "unbindTime",
            "orderable": false,
            "type": "date"

        }
    ],
    init: function () {
        var _this;
        _this = this;
        this._tableBox_ = document.querySelector("div.box.tableBox");
    },
    /**
     * 第一次搜索时由 refresh 调用
     */
    initDataTable: function () {
        var _this;
        _this = this;
        $.fn.dataTable.ext.errMode = 'none';
        this._dataTable_ = $("#bankCardAccountManageTable").DataTable({
            serverSide: true, //   是否开启服务器模式  true开启
            dom: 'lBrtip', //整个文档的结构
            scrollX: true, //设置水平滚动
            /* scrollY: "50vh",*/
            autoWidth: true, //控制Datatables是否自适应宽度
            searching: false,  //是否允许Datatables开启本地搜索
            columns: _this._columns_, //设定列的所有初始属性
            language: _this._language_, //DataTables语言配置选项
            //rowId: "name",//数据属性，Datatables在渲染的时候给 trTag设置的ID
            info: true, //控制是否显示表格左下角的信息
            processing: true, //是否显示加载的进程
            scrollCollapse: true, //当显示的记录不足一页时，是否允许表格减少高度
            colReorder: {     //打开和配置Datatables的ColReorder扩展
                fixedColumnsLeft: 2,//不允许第X列重新排序（从左往右数）
                fixedColumnsRight: 1//不允许第X列重新排序（从右往左数）
            },
            //buttons: [ 'copy', 'csv', 'excel' ],
            buttons: _this._getVisibleButton_(),  //所需要显示的按钮
            keys: false,   //先注释
            select: true, //先注释
            fixedColumns: {  //固定列   不太明白
                leftColumns: 2,
                rightColumns: 1
            },
            pagingType: "full_numbers",//分页显示  首页，尾页，上一页和下一页四个按钮,加上数字按钮
            ordering: false, //是否允许Datatables开启排序
            ajax: {
                url: _this._url_,
                type: "GET",
                data: function (data, settings) {
                    _this._data_(data, settings);
                },
                dataSrc: "data"
            }
        });
        this._dataTable_.on("select", function (e, dt, type, indexes) {
            BankCardAccountTableEventHandler.select(e, dt, type, indexes);
        });
        this._dataTable_.on("deselect", function (e, dt, type, indexes) {
            BankCardAccountTableEventHandler.deselect(e, dt, type, indexes);
        });
        BankCardAccountTableEventHandler.init(this._dataTable_);

    },
    /**
     *根据用户拥有的许可返回相应的按钮
     * @private
     */
    _getVisibleButton_: function () {
        let buttons;
        buttons = [];
        // if (ADMIN_HAS_DELETE_PERMISSION) {
        buttons.push(this._deleteButton_);
        //}

        //if (ADMIN_HAS_UPDATE_PERMISSION) {
        buttons.push(this._updateButton_);
        //}

        //if (ADMIN_HAS_CREATE_PERMISSION) {
        buttons.push(this._createButton_);
        //}
        return buttons;
    },
    _data_: function (data, settings) {
        var first, max;
        for (var key in data) {
            switch (key) {
                case "start":
                    first = data[key];
                    break;
                case "length":
                    max = data[key];
                    break;
                case "":
            }
            delete data[key];
        }
        data.page = first / max + 1;
        data.rows = max;
        $.extend(data, this._params_);
    },
    /**
     * 当 用户点击搜索按钮时调用此方法刷新 table
     * @param url
     * @param params
     */
    refresh: function (url, params) {
        // 先执行
        this._url_ = url;
        this._params_ = params;
        if (this._dataTable_ == null) {
            this.initDataTable();
        } else {
            this._dataTable_.ajax.url(this._url_).load();
        }
        this.showTableBox();

    },
    showTableBox: function () {
        if (this._tableBox_.classList.contains("hidden")) {
            this._tableBox_.classList.remove("hidden");
        }
    },
    hideTableBox: function () {
        if (!this._tableBox_.classList.contains("hidden")) {
            this._tableBox_.classList.add("hidden");
        }
    },
    getDataTable: function () {
        return this._dataTable_;
    }


};

const BankCardAccountTableEventHandler = {

    _dataTable_: null,

    _tableBox_: null,

    _table_: null,

    init: function (dataTable) {
        var table, _this;
        this._dataTable_ = dataTable;
        this._tableBox_ = document.querySelector("div.box.tableBox");
        this._table_ = this._tableBox_.querySelector("table.table");
        _this = this;
        this._table_.addEventListener("keydown", function (event) {
            _this.deleteKey(event);
        });
    },
    buttonAdd: function (e, dt, node, config) {
        BankCardAccountTableEditor.dialogEditor(dt, "add");
    },
    buttonDelete: function (e, dt, node, config) {
        var rowDatas, params, callBack;
        rowDatas = dt.rows({selected: true}).data();
        if (rowDatas.length != 1) {
            return;
        }
        //
        this._doDel_(rowDatas);
    },
    deleteKey: function (event) {
        if (event.which == 46 || event.keyCode == 46) {
            var rowDatas = this._dataTable_.rows({selected: true}).data();
            if (rowDatas.length != 1) {
                return;
            }
            this._doDel_(rowDatas);
        }
    },
    _doDel_: function (rowDatas) {
        var params, callBack, _this;
        params = new Params();
        params["name"] = rowDatas[0].name;
        _this = this;
        callBack = function (data) {
            if (data.status === true) {
                $.notify({
                    icon: 'glyphicon glyphicon-leaf',
                    title: "通知",
                    message: "删除 bankCardAccount [ " + (data.data ? data.data.name : "--") + " ] 成功"
                }, {
                    type: "success",
                    mouse_over: "pause",
                    delay: 3000,
                    placement: {
                        align: "center"
                    },
                    animate: {
                        enter: "animated",
                        exit: "animated"
                    }
                });
                // 刷新当前页
                _this._dataTable_.ajax.reload(null, false);
            } else {
                BootstrapDialog.alert({
                    title: '错误',
                    message: data.message,
                    type: BootstrapDialog.TYPE_DANGER,
                    closable: true,
                    draggable: true,
                    buttonLabel: '确认',
                });
            }
        };
        BootstrapDialog.confirm({
            title: '警告',
            message: "确定要删除 [ " + rowDatas[0].name + " ] 吗?",
            type: BootstrapDialog.TYPE_WARNING,
            closable: true,
            draggable: true,
            btnCancelLabel: '取消',
            btnOKLabel: '确认',
            btnOKClass: 'btn-warning',
            callback: function (result) {
                if (result) {
                    $.post(RoamCloudManage.userPath + "/resource/delBankCardAccount", params, callBack, "json");
                }
            }
        });
    },
    buttonEdit: function (e, dt, node, config) {
        if (dt.rows({selected: true}).count() == 1) {
            BankCardAccountTableEditor.dialogEditor(dt, "edit")
        }
    },
    select: function (e, dt, type, indexes) {
        DataTableUtils.decisionButtonVisible(dt);
    },
    deselect: function (e, dt, type, indexes) {
        DataTableUtils.decisionButtonVisible(dt);
    }

};

const BankCardAccountTableEditor = {

    _dialogDiv_: null,

    _dialogEditor_: null,

    _initDialogEditor_: function () {
        var _this, e;
        _this = this;
        this._dialogDiv_ = document.querySelector("#bankCardAccountEditDialog");
        this._dialogEditor_ = $("#bankCardAccountEditDialog").modal({
            show: false,
            keyboard: true,
            backdrop: "static"
        });
        // 提交按钮
        e = document.querySelector("#editorFormSubmit");
        e.addEventListener("click", function () {
            _this.save(this);
        });
        // BaseOrderTableEditorValidator.init();
    },
    /**
     *
     * @param dt dataTable 对象
     * @param type [add,edit]
     */
    dialogEditor: function (dt, type) {
        if (this._dialogEditor_ == null) {
            this._initDialogEditor_();
        }
        switch (type) {
            case 'edit':
                var row, rowData;
                row = dt.row({selected: true});
                rowData = row.data();
                this._initForEdit_(row.index(), rowData);
                break;
            case 'add':
            default:
                this._initForAdd_();
        }

        this._dialogEditorProtected_(false);
        this._dialogEditor_.modal("show");
    },
    _initForEdit_: function (rowIndex, rowData) {
        var group, form, e;
        this._dialogDiv_.querySelector("#bankCardAccountEditDialogTitle").innerHTML = "BankCardAccount[" + rowData.mac + "]编辑";

        form = this._dialogDiv_.querySelector("#bankCardAccountEditorForm");
        form.setAttribute("data-editType", "edit");
        form.setAttribute("data-rowIndex", rowIndex);
        form.setAttribute("data-mac", rowData.mac);
        e = form.querySelector("input[name='address']");
        e.value = rowData.address;

        group = this._dialogDiv_.querySelector("div.form-group.mac");
        group.classList.remove("show");
        group.classList.add("hidden");
    },
    _initForAdd_: function () {
        var group, form, e;
        this._dialogDiv_.querySelector("#bankCardAccountEditDialogTitle").innerHTML = "BankCardAccount 添加";

        form = this._dialogDiv_.querySelector("#bankCardAccountEditorForm");
        form.setAttribute("data-editType", "add");
        form.setAttribute("data-rowIndex", null);
        form.setAttribute("data-mac", null);
        e = form.querySelector("input[name='mac']");
        e.value = "";
        e = form.querySelector("input[name='address']");
        e.value = "";

        group = this._dialogDiv_.querySelector("div.form-group.mac");
        group.classList.remove("hidden");
        group.classList.add("show");
    },
    /**
     *
     * @param isProtected Boolean
     * @private
     */
    _dialogEditorProtected_: function (isProtected) {
        var submitBtn, cancelBtn, editorArray, editor, disabled;
        submitBtn = document.querySelector("#editorFormSubmit");
        cancelBtn = document.querySelector("#editorFormCancel");
        cancelBtn.disabled = isProtected;
        submitBtn.disabled = isProtected;
        if (isProtected) {
            cancelBtn.classList.add("disabled");
            submitBtn.classList.add("disabled");
        } else {
            cancelBtn.classList.remove("disabled");
            submitBtn.classList.remove("disabled");
        }
        editorArray = submitBtn.form.querySelectorAll(".editor");
        for (var i = 0; i < editorArray.length; i++) {
            editor = editorArray[i];
            if (isProtected) {
                editor.classList.add("disabled");
            } else {
                editor.classList.remove("disabled");
            }
            editor.disabled = isProtected;
        }
    },
    save: function (btn) {
        this._dialogEditorProtected_(true);
        var form, editorArray, i, editor, value, params, callBack, editType, url, _this;
        form = btn.form;
        editorArray = form.querySelectorAll(".editor");
        params = new Params();
        editType = form.getAttribute("data-editType");
        if (editType == "edit") {
            params.mac = form.getAttribute("data-mac");
        }
        for (i = 0; i < editorArray.length; i++) {
            editor = editorArray[i];
            if (editor.classList.contains("validate")
                && editor.getAttribute("data-validate") == "error") {
                this._dialogEditorProtected_(false);
                return;
            }
            if (editor.name == "mac" && editType == "edit") {
                continue;
            }
            value = editor.getAttribute("data-value");
            if (value != null && value != "") {
                params[editor.name] = value;
            } else {
                params[editor.name] = editor.value;
            }
        }
        _this = this;
        callBack = editType == "edit" ? function (data) {
            _this._editCallBack_(data);
        } : function (data) {
            _this._addCallBack_(data);
        };
        url = editType == "edit" ? "/resource/editBankCardAccount" : "/resource/addBankCardAccount";
        $.post(RoamCloudManage.userPath + url, params, callBack, "json");

    },
    _editCallBack_: function (data) {
        var message, form;
        form = this._dialogDiv_.querySelector("#bankCardAccountEditorForm");
        this._dialogEditor_.modal("hide");
        this._dialogEditorProtected_(false);
        if (data.status) {
            var row, rowIndex;
            rowIndex = parseInt(form.getAttribute("data-rowIndex"));
            row = BankCardAccountTableBox.getDataTable().row(rowIndex);
            row.data(data.data);
            $.notify({
                icon: 'glyphicon glyphicon-leaf',
                title: "通知",
                message: "编辑bankCardAccount [ " + data.data.mac + " ] 成功"
            }, {
                type: "success",
                mouse_over: "pause",
                delay: 3000,
                placement: {
                    align: "center"
                },
                animate: {
                    enter: "animated",
                    exit: "animated"
                }
            });
        } else {
            message = data.message;
            if (data.validateDetail != null) {
                message += "<br/>";
                for (var key in data.validateDetail) {
                    message += key + " : " + data.validateDetail[key];
                    message += "<br/>";
                }
            }
            BootstrapDialog.alert({
                title: '错误',
                message: message,
                type: BootstrapDialog.TYPE_DANGER,
                closable: true,
                draggable: true,
                buttonLabel: '确认',
            });
        }

    },
    _addCallBack_: function (data) {
        var message;
        this._dialogEditor_.modal("hide");
        this._dialogEditorProtected_(false);
        if (data.status) {
            message = data.message + "(已刷新本页),<strong class='text-danger'>新数据 不一定显示在本页</strong>";
            message += "<br/>";
            for (var key in data.data) {
                message += key + " : " + data.data[key];
                message += "<br/>";
            }
            BootstrapDialog.alert({
                title: '通知',
                message: message,
                type: BootstrapDialog.TYPE_SUCCESS,
                closable: true,
                draggable: true,
                buttonLabel: '确认',
            });
            BankCardAccountTableBox.getDataTable().draw(false);
        } else {
            message = data.message;
            if (data.validateDetail != null) {
                message += "<br/>";
                for (var key in data.validateDetail) {
                    message += key + " : " + data.validateDetail[key];
                    message += "<br/>";
                }
            }
            BootstrapDialog.alert({
                title: '错误',
                message: message,
                type: BootstrapDialog.TYPE_DANGER,
                closable: true,
                draggable: true,
                buttonLabel: '确认',
            });
        }


    }

};